package com.bing.my.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bing.my.entity.Member;
import com.bing.my.entity.Recharge;
import com.bing.my.mapper.MemberMapper;
import com.bing.my.mapper.RechargeMapper;
import com.bing.my.service.RechargeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.istack.internal.NotNull;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;

/**
 * <p>
 * 充值数据 服务实现类
 * </p>
 *
 * @author bing
 * @since 2021-10-20
 */
@Service
@Log4j2
public class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements RechargeService {

    @Resource
    private RechargeMapper rechargeMapper;
    @Resource
    private MemberMapper memberMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMoney(@NotNull Recharge recharge,@NotNull String id) {
        try {
            recharge.setMemberId(id);
            // 添加充值记录
            rechargeMapper.insert(recharge);
            // 查询会员
            Member member = memberMapper.selectById(id);
            // 进行修改充值
            member.setBalance(member.getBalance().add(recharge.getMoney()));
            memberMapper.updateById(member);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("充值失败======>"+e);
            // 手动强制回滚事务，这里一定要第一时间处理
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

    }

    @Override
    public Page<Recharge> selectPage(Integer pageNum, Integer pageSize, String memberId) {
        Page<Recharge> selectPage = rechargeMapper.selectPage(new Page<>(pageNum, pageSize),
                Wrappers.<Recharge>lambdaQuery().eq(Recharge::getMemberId, memberId)
                        // 根据创建时间倒序
                        .orderByDesc(Recharge::getGmtCreate));
        return selectPage;
    }

    @Override
    public int update(Recharge recharge) {
        return rechargeMapper.updateById(recharge);
    }

    @Override
    public int deleteById(String id) {
        return rechargeMapper.deleteById(id);
    }
}
